﻿/***************************
* 1.随手拍
****************************/

//CheckPopLogin_Menu(function () {
    /* 变量 */
    var myshowscene = "experience/myshowscene.html";
    var myshowsceneDetail = "experience/myshowsceneDetail.html";

    //临时 用户id
    //var currentUserId = "15871720272";
    var currentUserId = iss_localStorage.get("yuqing_appPhone");
    /* 我秀我景--列表 */
    var contactsCallback_myshowscene = myApp.onPageInit('myshowscene', function (page) {
        var Now_userId; //当前查找的用户

        $$("#myshowscene_page .upload-loc span").html(ISS_Constants.User.city);

        //删除滚动后重新添加滚动
        var flag_InfiniteScroll = true;
        //是否需要滚动加载
        var flag_needScroll = true;
        //滚动事件只执行一次
        var flag_execute = false;

        var index_tab1 = 1;

        var size = 10;
        myApp.attachInfiniteScroll($$('#myshowscene_page .infinite-scroll'));
        $$('#myshowscene_page .infinite-scroll').scrollTop(0);
        // 默认加载 第一个
        LoadData(index_tab1, size, "0");

        // 加载数据
        function LoadData(pageindex, pagesize, userId) {
//            if (currentUserId == "") return;
            Now_userId = userId;
            // 参数
            var conditionParams = {
                type: 3,
                content: JSON.stringify({ 
                    calltype: "2",
                    jsonParm: {
                        pageIndex: pageindex,
                        pageSize: pagesize,
                        currentUserId: currentUserId,
                        userId: userId
                    },
                }),
            };
            $$.ajax({
                url: ISS_Constants.Url.const_sns_url,
                data: conditionParams,
                dataType: "jsonp",
                success: function (datas, status) {
                    data = eval('(' + datas + ')');
                    if (data && data.refresh && data.result.length > 0) {
                        // 格式化数据
                        for (var i = 0; i < data.result.length; i++) {
                            if (data.result[i].Imgs == undefined) {
                                data.result[i].Imgs = {
                                    url: NoPicture()
                                };
                            }
                            if (data.result[i].Imgs.length == 1) {
                                data.result[i].imghtml = "<div class='row'><div class='col-100' style='background-image: url(" + data.result[i].Imgs[0].url + ");'></div></div>";
                            }
                            else {
                                var imghtml = "";
                                if (data.result[i].Imgs.length == 2 || data.result[i].Imgs.length == 4) {
                                    for (var j = 0; j < data.result[i].Imgs.length; j++) {
                                        if (j == 0 || j == 2) {
                                            imghtml += "<div class='row'>";
                                        }
                                        imghtml += "<div class='col-50' style='background-image: url(" + data.result[i].Imgs[j].url + ");'></div>";
                                        if (j == 1 || j == 3) {
                                            imghtml += "</div>";
                                        }
                                    }
                                }
                                else if (data.result[i].Imgs.length == 3 || data.result[i].Imgs.length == 6) {
                                    for (var j = 0; j < data.result[i].Imgs.length; j++) {
                                        if (j == 0 || j == 3) {
                                            imghtml += "<div class='row'>";
                                        }
                                        imghtml += "<div class='col-33' style='background-image: url(" + data.result[i].Imgs[j].url + ");'></div>";
                                        if (j == 2 || j == 5) {
                                            imghtml += "</div>";
                                        }
                                    }
                                }
                                else if (data.result[i].Imgs.length == 5) {
                                    for (var j = 0; j < data.result[i].Imgs.length; j++) {
                                        if (j == 0 || j == 3) {
                                            imghtml += "<div class='row'>";
                                        }
                                        if (j < 3) {
                                            imghtml += "<div class='col-33' style='background-image: url(" + data.result[i].Imgs[j].url + ");'></div>";
                                        } else {
                                            imghtml += "<div class='col-50' style='background-image: url(" + data.result[i].Imgs[j].url + ");'></div>";
                                        }
                                        if (j == 2 || j == 5) {
                                            imghtml += "</div>";
                                        }
                                    }
                                }

                                data.result[i].imghtml = imghtml;
                            }

                            data.result[i].Body = decodeURIComponent(data.result[i].Body);
                            data.result[i].DateCreated = getDatedif(data.result[i].DateCreated);
                        }
                        var searchTemplate = $$('#template-myshowscene-tab1').html();
                        if (searchTemplate) {
                            var compiledTemplate = Template7.compile(searchTemplate);
                            var html = compiledTemplate(data);
                            $$("div.page-content span").append(html);
                            flag_InfiniteScroll = flag_needScroll = true;
                        }
                        //tab1综合,无限滚动只加载一次
                        if (!flag_execute) {
                            //只执行一次
                            flag_execute = true;

                            // 加载flag
                            var loading = false;
                            //查询时,删除滚动后重新绑定pageindex
                            if (!flag_InfiniteScroll) {
                                flag_InfiniteScroll = true;
                                return;
                            }
                            $$('#myshowscene_page .infinite-scroll').on('infinite', function () {
                                // 如果正在加载，则退出
                                if (loading) return;
                                // 设置flag
                                loading = true;
                                // 模拟1s的加载过程
                                setTimeout(function () {
                                    // 重置加载flag
                                    loading = false;
                                    index_tab1++;
                                    LoadData(index_tab1, size, userId);
                                }, 100);
                            });
                        }
                        if ($$("page-content .card.facebook-card").length >= data.total) {
                            // 删除加载提示符
                            $$('#myshowscene_page .infinite-scroll-preloader1').remove();
                            // 加载完毕，则注销无限加载事件，以防不必要的加载
                            myApp.detachInfiniteScroll($$('#myshowscene_page .infinite-scroll'));
                        }

                    }
                    else {
                        // 删除加载提示符
                        myApp.detachInfiniteScroll($$('#myshowscene_page .infinite-scroll'));
                        $$('#myshowscene_page .infinite-scroll-preloader1').remove();
                        index_tab1--;

                    }
                },
                error: function (xhr, status) {
                    console.log("ajax error!");

                }
            });

        };

        //点赞
        $$("div.page-content.infinite-scroll").on("click", "a.link.zan", function () {
            if ($$(this).hasClass("active")) return;
            // 参数
            var conditionParams = {
                type: 3,
                content: JSON.stringify({ 
                    calltype: "3",
                    jsonParm: {
                        currentUserId: currentUserId,
                        threadId: $$(this).attr("threadId")
                    },
                }),
            };
            var this_a = $$(this);
            $$.ajax({
                url: ISS_Constants.Url.const_sns_url,
                data: conditionParams,
                dataType: "jsonp",
                success: function (datas, status) {
                    data = eval('(' + datas + ')');
                    if (data && data.refresh) {
                        $$(this_a).addClass("active");
                        var PraiseCount = $$(this_a).text();
                        PraiseCount = parseInt(PraiseCount);
                        PraiseCount++;
                        $$(this_a).html("<i class='iconfont icon-zan'></i>" + PraiseCount.toString());
                    }
                    else {
                        myApp.alert(data.failMsg);
                    }
                },
                error: function (xhr, status) {
                    console.log("ajax error!");
                }
            });
        })


        /*
        * 上传图片
        *
        */

        $$("div.popup.popup-about span").on("change", "input[type='file']", function () {
            var imgs = $$("#upload-container div");
            if (imgs.length >= 6) {
                myApp.alert("最多只能上传6张照片");
                return;
            }
            var that = $$(this);

            lrz(that[0].files[0], {
                width: 800
            })
        .then(function (rst) {
            var img = new Image();
            var div = document.createElement('div');
            div.className = 'col-33';
            $$(div).css("background-image", "url(" + rst.base64 + ")");
            //$$(div).attr("FileName", rst.origin.name);
            //$$(div).attr("type", rst.origin.type);
            //$$(div).attr("data", rst.base64);

            var _conditionParm = JSON.stringify({
                FileName: rst.origin.name,
                type: rst.origin.type,
                img: rst.base64
            });
            myApp.showPreloader();
            $$.ajax({
                url: ISS_Constants.Url.const_myshowscene_add_uploadloacl,
                data: { "conditionParm": _conditionParm },
                crossDomain: true,
                method: "POST",
                dataType: "jsonp",
                success: function (data, status) {
                    myApp.hidePreloader();
                    data = JSON.parse(data);
                    if (data && data.success) {
                        $$(div).attr("saveFileName", data.datas.saveFileName); //本地保存文件名
                        $$(div).attr("path", data.datas.path); //本地保存路径
                        $$('#upload-container').append(div);
                        return rst;
                    }
                },
                error: function (xhr, status) { myApp.hidePreloader(); }
            });




        });
        })
        //保存
        $$("#btn-save").click(function () {

            var body = $$("#txt_body").val();
            if (body == "") {
                myApp.alert("请输入内容！");
                return;
            }
            var imgs = $$("#upload-container div");
            if (imgs.length > 6) {
                myApp.alert("最多只能上传6张照片");
                return;
            }
            var ImgList = [];
            myApp.showPreloader();
            $$("#upload-container div").each(function () {
                var imgitem = {
                    //                FileName: $$(this).attr("FileName"),
                    //                type: $$(this).attr("type"),
                    //                //img: $$(this).css("background-image").replace("url(", "").replace(")", "")
                    //                img: $$(this).attr("data")
                    saveFileName: $$(this).attr("saveFileName"),
                    path: $$(this).attr("path")
                };
                ImgList.push(imgitem);
            });

            // 参数
            var conditionParams = {
                type: 3,
                action: 10,
                content: JSON.stringify({ 
                    calltype: "0",
                    jsonParm: {
                        currentUserId: currentUserId,
                        body: body,
                        lng:'',
                        lat:'',
                        location:'',
                    },
                }),
                imageList: JSON.stringify(ImgList),
            };

            $$.ajax({
                url: ISS_Constants.Url.const_sns_url,
                data: conditionParams,
                dataType: "jsonp",
                success: function (datas, status) {
                    myApp.hidePreloader();
                    data = eval('(' + datas + ')');
                    if (data && data.refresh) {
                        myApp.alert("上传成功！");
                        myApp.closeModal(".popup-about");
                        return;
                    } else {
                        myApp.alert(data.failMsg);
                    }
                },
                error: function (xhr, status) { myApp.hidePreloader(); }
            });

        })

        $$('.popup-about').on('closed', function () {
            $$("#txt_body").val("");
            $$("#upload-container").html("");
            $$("div.popup.popup-about span").html("<input accept=\"image/*\" type=\"file\" style=\" font-size:0; width:50px; height:30px; display:block; opacity:0;\" />");
        });

        function toFixed2(num) {
            return parseFloat(+num.toFixed(2));
        }

        //点击头像，加载当前用户查询条件
        $$("#myshowscene_page .page-content").on("click", ".userImg", function () {
            var data = $$(this).attr("data");
            if (data != "") {
                if (Now_userId == data) return; //如果当前查找条件满足点击，不重新加载
                $$("#myshowscene_page div.page-content span").html("");
                $$('#myshowscene_page .infinite-scroll').scrollTop(0);
                LoadData("1", size, data);
            }
        })


        //下拉刷新
        var ptrContent = $$('.pull-to-refresh-content');
        // 添加'refresh'监听器
        ptrContent.on('refresh', function (e) {
            // 模拟2s的加载过程
            setTimeout(function () {
                $$("#myshowscene_page div.page-content span").html("");
                $$('#myshowscene_page .infinite-scroll').scrollTop(0);
                LoadData("1", size, Now_userId);
                // 加载完毕需要重置
                myApp.pullToRefreshDone();
            }, 2000);
        });

    });

    /* 我秀我景--详情 */
    var contactsCallback_myshowsceneDetail = myApp.onPageInit('myshowsceneDetail', function (page) {
        var threadId = ISS.utils.getParameter("threadId");
        if (page != undefined) {
            threadId = page.query.threadId;
        }
        LoadDetailData();
        var myPhotoBrowserStandalone;
        //详情
        function LoadDetailData() {
            // 参数 详情
            var conditionParams = {
                type: 3,
                content: JSON.stringify({ 
                    calltype: "8",
                    jsonParm: {
                        currentUserId: currentUserId,
                        threadId: threadId
                    },
                }),
            };
            $$.ajax({
                url: ISS_Constants.Url.const_sns_url,
                data: conditionParams,
                dataType: "jsonp",
                success: function (datas, status) {
                    data = eval('(' + datas + ')');
                    if (data && data.refresh && data.result) {
                        // 格式化数据

                        if (data.result.Imgs == undefined) {
                            data.result.Imgs = {
                                url: NoPicture()
                            };
                        }
                        var photos = [];
                        for (var i = 0; i < data.result.Imgs.length; i++) {
                            photos.push(data.result.Imgs[i].url);
                        }
                        myPhotoBrowserStandalone = myApp.photoBrowser({ photos: photos, theme: 'dark' });
                        if (data.result.Imgs.length == 1) {
                            data.result.imghtml = "<div class='row'><div class='col-100 img' style='background-image: url(" + data.result.Imgs[0].url + ");'></div></div>";
                        }
                        else {
                            var imghtml = "";
                            if (data.result.Imgs.length == 2 || data.result.Imgs.length == 4) {
                                for (var j = 0; j < data.result.Imgs.length; j++) {
                                    if (j == 0 || j == 2) {
                                        imghtml += "<div class='row'>";
                                    }
                                    imghtml += "<div class='col-50 img' style='background-image: url(" + data.result.Imgs[j].url + ");'></div>";
                                    if (j == 1 || j == 3) {
                                        imghtml += "</div>";
                                    }
                                }
                            }
                            else if (data.result.Imgs.length == 3 || data.result.Imgs.length == 6) {
                                for (var j = 0; j < data.result.Imgs.length; j++) {
                                    if (j == 0 || j == 3) {
                                        imghtml += "<div class='row'>";
                                    }
                                    imghtml += "<div class='col-33 img' style='background-image: url(" + data.result.Imgs[j].url + ");'></div>";
                                    if (j == 2 || j == 5) {
                                        imghtml += "</div>";
                                    }
                                }
                            }
                            else if (data.result.Imgs.length == 5) {
                                for (var j = 0; j < data.result.Imgs.length; j++) {
                                    if (j == 0 || j == 3) {
                                        imghtml += "<div class='row'>";
                                    }
                                    if (j < 3) {
                                        imghtml += "<div class='col-33 img' style='background-image: url(" + data.result.Imgs[j].url + ");'></div>";
                                    } else {
                                        imghtml += "<div class='col-50 img' style='background-image: url(" + data.result.Imgs[j].url + ");'></div>";
                                    }
                                    if (j == 2 || j == 5) {
                                        imghtml += "</div>";
                                    }
                                }
                            }

                            data.result.imghtml = imghtml;
                        }
                        data.result.Body = decodeURIComponent(data.result.Body);
                        data.result.DateCreated = getDatedif(data.result.DateCreated);
                        data.result.UserImg = ISS_Constants.Url.const_user_img + data.result.Author;
                        var searchTemplate = $$('#myshowsceneDetail_page #template-myshowscene-tab1').html();
                        if (searchTemplate) {
                            var compiledTemplate = Template7.compile(searchTemplate);
                            var html = compiledTemplate(data.result);
                            $$("div.page-content span#detail").append(html);
                        }
                        if (data.result.IsPraised) {
                            $$("#myshowsceneDetail_page div.toolbar a.link.zan").addClass("active");
                        }
                        else {
                            $$("#myshowsceneDetail_page div.toolbar a.link.zan").removeClass("active");
                        }
                    }
                },
                error: function (xhr, status) {
                    console.log("ajax error!");

                }
            });
        }
        //图片浏览器
        $$('#myshowsceneDetail_page div.page-content').on("click", "div.img", function () {
            myPhotoBrowserStandalone.open();
        })

        //删除滚动后重新添加滚动
        var flag_InfiniteScroll = true;
        //是否需要滚动加载
        var flag_needScroll = true;
        //滚动事件只执行一次
        var flag_execute = false;

        var index_tab1 = 1;

        var size = 5;
        myApp.attachInfiniteScroll($$('#myshowsceneDetail_page .infinite-scroll'));
        $$('#myshowsceneDetail_page .infinite-scroll').scrollTop(0);
        // 默认加载 第一个
        LoadPLData(index_tab1, size);

        //评论列表
        function LoadPLData(pageindex, pagesize) {
            // 参数
            var conditionParams = {
                type: 3,
                content: JSON.stringify({ 
                    calltype: "4",
                    jsonParm: {
                        pageIndex: pageindex,
                        pageSize: pagesize,
                        threadId: threadId
                    },
                }),
            };
            $$.ajax({
                url: ISS_Constants.Url.const_sns_url,
                data: conditionParams,
                dataType: "jsonp",
                success: function (datas, status) {
                    data = eval('(' + datas + ')');
                    if (data && data.refresh && data.result.length > 0) {
                        $$("div.content-block-title span").html("评论&nbsp;" + data.TotalRecords);
                        for (var i = 0; i < data.result.length; i++) {
                            data.result[i].Body = decodeURIComponent(data.result[i].Body);
                            data.result[i].DateCreated = getDateMDMS(data.result[i].DateCreated);
                            data.result[i].UserImg = ISS_Constants.Url.const_user_img + data.result[i].Author;
                        }
                        var searchTemplate = $$('#template-myshowscene-detail').html();
                        if (searchTemplate) {
                            var compiledTemplate = Template7.compile(searchTemplate);
                            var html = compiledTemplate(data);
                            $$("div.list-block.media-list ul").append(html);
                            flag_InfiniteScroll = flag_needScroll = true;

                        }
                        //tab1综合,无限滚动只加载一次
                        if (!flag_execute) {
                            //只执行一次
                            flag_execute = true;

                            // 加载flag
                            var loading = false;
                            //查询时,删除滚动后重新绑定pageindex
                            if (!flag_InfiniteScroll) {
                                flag_InfiniteScroll = true;
                                return;
                            }
                            $$('#myshowsceneDetail_page .infinite-scroll').on('infinite', function () {
                                // 如果正在加载，则退出
                                if (loading) return;
                                // 设置flag
                                loading = true;
                                // 模拟1s的加载过程
                                setTimeout(function () {
                                    // 重置加载flag
                                    loading = false;
                                    index_tab1++;
                                    LoadPLData(index_tab1, size);
                                }, 100);
                            });
                        }
                        if ($$("list-block ul li").length >= data.TotalRecords || data.result.length >= data.TotalRecords) {

                            // 加载完毕，则注销无限加载事件，以防不必要的加载
                            myApp.detachInfiniteScroll($$('#myshowsceneDetail_page .infinite-scroll'));
                            // 删除加载提示符
                            $$('#myshowsceneDetail_page .infinite-scroll-preloader1').remove();
                        }
                    }
                    else {
                        // 删除加载提示符
                        myApp.detachInfiniteScroll($$('#myshowsceneDetail_page .infinite-scroll'));
                        $$('#myshowsceneDetail_page .infinite-scroll-preloader1').remove();
                        index_tab1--;

                    }
                },
                error: function (xhr, status) {
                    console.log("ajax error!");

                }
            });
        }

        $$('.open-pinglun').on('click', function () {
            myApp.pickerModal('.picker-pinglun');
        });

        //添加评论
        $$(".btn_submit").on('click', function () {
            var body = $$(".picker-pinglun #txt_body").val();
            if (body == "") {
                myApp.alert("请输入评论内容！");
                return;
            }
            // 参数 回复添加
            var conditionParams = {
                type: 3,
                content: JSON.stringify({ 
                    calltype: "5",
                    jsonParm: {
                        currentUserId: currentUserId,
                        body: body,
                        threadId: threadId
                    },
                }),
            };
            $$.ajax({
                url: ISS_Constants.Url.const_sns_url,
                data: conditionParams,
                dataType: "jsonp",
                success: function (datas, status) {
                    data = eval('(' + datas + ')');
                    if (data && data.refresh) {
                        $$(".picker-pinglun #txt_body").val("");
                        myApp.closeModal('.picker-pinglun');
                        $$("div.list-block.media-list ul li").remove();


                        myApp.alert("提交成功！", function () {
                            index_tab1 = 1;
                            myApp.attachInfiniteScroll($$('#myshowsceneDetail_page .infinite-scroll'));
                            $$('#myshowsceneDetail_page .infinite-scroll').scrollTop(0);
                            LoadPLData(index_tab1, size);
                        });
                    }
                    else {
                        myApp.alert(data.failMsg);
                    }
                },
                error: function (xhr, status) {
                    console.log("ajax error!");
                }
            });
        });


        //点赞
        $$("div.toolbar").on("click", "a.link.zan", function () {
            if ($$(this).hasClass("active")) return;
            var _content = JSON.stringify({
                currentUserId: currentUserId,
                threadId: threadId
            });
            var this_a = $$(this);
            $$.ajax({
                url: ISS_Constants.Url.const_myshowscene_praised,
                data: { jsonParm: _content },
                crossDomain: true,
                dataType: "json",
                success: function (datas, status) {
                    data = eval('(' + datas + ')');
                    if (data && data.refresh) {
                        $$(this_a).addClass("active");
                    }
                    else {
                        myApp.alert(data.failMsg);
                    }
                },
                error: function (xhr, status) {
                    console.log("ajax error!");
                }
            });
        })

        $$(".picker-pinglun #txt_body").keyup(function () {
            var body = $$(this).val();
            if (body.length > 200) {
                body = body.substring(0, 200);
            }
            $$("#txt_body").val(body);
            var max = 200;
            var less = max - body.length;
            $$(".textarealength span").html(less);
        });
    });

    /* 初始化  */
    function initData() {
        var href = window.location.href;
        if (href.indexOf(myshowscene) > -1) {
            contactsCallback_myshowscene.trigger();
        }
        else if (href.indexOf(myshowsceneDetail) > -1) {
            contactsCallback_myshowsceneDetail.trigger();
        }
    }

    initData();

    //获取时间（1小时前,1分钟前..）
    function getDatedif(olddate) {
        var date1 = olddate.replace(/-/g, "/");
        date1 = new Date(date1);
        var date = new Date();  //当前时间
        var date3 = date.getTime() - date1.getTime()  //时间差的毫秒数
        //计算出相差天数
        var days = Math.floor(date3 / (24 * 3600 * 1000));
        if (days >= 1) {
            return olddate;
        }
        //计算小时数
        var leave1 = Math.floor(date3 / (3600 * 1000));
        if (leave1 >= 1) {
            return leave1 + "小时前";
        }
        //计算相差分钟数
        var leave2 = Math.floor(date3 / (60 * 1000));
        if (leave2 >= 1) {
            return leave2 + "分钟前";
        }
        //计算相差秒数
        var leave3 = Math.floor(date3 / (60 * 1000));
        if(leave3 <= 0){
             return "刚刚";
        }
        return leave3 + "秒前";
    }

    //获取时间格式：2016-05-27 16:54:49 转变为：5-31 15:26
    function getDateMDMS(olddate) {
        var date1 = olddate.replace(/-/g, "/");
        date1 = new Date(date1);
        return (date1.getMonth() + 1).toString() + "-" + date1.getDate().toString() + "&nbsp;" + date1.getHours() + ":" + date1.getMinutes();
    }

    $$('.publish').on('click',function(){
        CheckPopLogin(function () {
        });
    });
//});